﻿using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class SysAttachmentDal
    {
        private readonly AppDbContext _dbContext;
        private string URL;
        public SysAttachmentDal(AppDbContext dbContext)
        {
            dynamic jsonObject = JsonConvert.DeserializeObject(File.ReadAllText("appsettings.json"));
            URL = jsonObject.ConnectionStrings.SqlServer;
            _dbContext = dbContext;
        }

        public async Task<int> UploadAttachment(List<SysAttachmentDTO> sadtoList)
        {
            if (sadtoList == null || sadtoList.Count == 0)
            {
                return 0; // 空列表直接返回
            }

            // 转换：仅复制DTO中存在的字段，忽略映射类的主键
            var attachmentEntities = sadtoList.Select(dto => new SysAttachment
            {
                // 只赋值DTO中有的字段，Id不赋值
                AttachmentCode = dto.AttachmentCode,
                AttachmentAddress = dto.AttachmentAddress,
                IsDelete = "0",
                CreateBy = dto.CreateBy,
                CreateTime = dto.CreateTime,
                UpdateBy = dto.UpdateBy,
                UpdateTime = dto.UpdateTime
            }).ToList();

            // 批量添加到数据库
            _dbContext.SysAttachment.AddRange(attachmentEntities);
            return await _dbContext.SaveChangesAsync(); // 保存后，数据库自动生成Id
        }
    }
}
